package xuanzi.weapp;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.StringReader;
import java.util.Set;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.commons.io.FileUtils;

import com.google.gwt.core.ext.LinkerContext;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.core.ext.linker.AbstractLinker;
import com.google.gwt.core.ext.linker.ArtifactSet;
import com.google.gwt.core.ext.linker.CompilationResult;
import com.google.gwt.core.ext.linker.LinkerOrder;
import com.google.gwt.core.ext.linker.LinkerOrder.Order;
import com.google.gwt.core.ext.linker.ScriptReference;
import com.google.gwt.dev.json.JsonException;
import com.google.gwt.dev.json.JsonObject;
import com.google.gwt.dev.util.DefaultTextOutput;

import xuanzi.xzmind.Build;

/**
 *  
 * 
 * @author 彭立铭
 */
@LinkerOrder(Order.PRIMARY)
public class XZMindWeAppLinker extends AbstractLinker {
	
    @Override
    public String getDescription() {
        return "WeAppLinker";
    }
    
    @Override
    public ArtifactSet relink(TreeLogger logger, LinkerContext context, ArtifactSet newArtifacts)
    		throws UnableToCompleteException {
    	System.out.println("relink");
    	return super.relink(logger, context, newArtifacts);
    }
    
    @Override
    public ArtifactSet link(TreeLogger logger, LinkerContext context, ArtifactSet artifacts, boolean onePermutation)
    		throws UnableToCompleteException {
    	System.out.println("link");
    	return super.link(logger, context, artifacts, onePermutation);
    }
    
    @Override
    public boolean supportsDevModeInJunit(LinkerContext context) {
    	// TODO Auto-generated method stub
    	return super.supportsDevModeInJunit(context);
    }

    @Override
    public ArtifactSet link(TreeLogger logger, LinkerContext context,
            ArtifactSet artifacts) throws UnableToCompleteException {
    	
    	
        ArtifactSet toReturn = new ArtifactSet(artifacts);
        DefaultTextOutput out = new DefaultTextOutput(true);
        doScriptLicense(out);
        doAppConfig(context,out);
        doScriptHeader(context,out);
        doScriptBody(context,out);
        {
	        Set<CompilationResult> results = artifacts.find(CompilationResult.class);
	        CompilationResult result = null;
	         if (!results.isEmpty()) {
	            result = results.iterator().next();
	            // dump JS
	            String[] js = result.getJavaScript();
	            if (js.length != 1) {
	                logger.log(TreeLogger.ERROR,
	                        "The module must not have multiple fragments when using the "
	                                + getDescription() + " Linker.", null);
	                throw new UnableToCompleteException();
	            }
	            out.print(js[0]);
	            System.out.println("//module:");
	         }
	        out.newline(); 
	        addPreloadCode(logger, context, artifacts, result, out);
	        out.newline(); 
        }
        //and to string
        doScriptFooter(context,out);
        toReturn.add(emitString(logger, out.toString(), "../"+context.getModuleName() + ".js"));
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
			
			@Override
			public void run() {
				buildFiles();
			}
		}, 300);
        System.out.println("编译结束");
        out.print("// 玄子科技出品");
        return toReturn;
    }
    
    protected void buildFiles() {
		// TODO Auto-generated method stub
		Build build = new Build();
		build.build();
	}

	protected void doAppConfig(LinkerContext context, DefaultTextOutput out) { 
    	String s;
		try {
			s = FileUtils.readFileToString(new File("appbuild.json"), "UTF-8");
			System.out.println(s);
		} catch (IOException e) { 
			e.printStackTrace();
		}
	}

    protected void doScriptFooter(LinkerContext context, DefaultTextOutput out) {
    	  out.print("window.onload = function(){\n");
          out.print("\tgwtOnLoad(null, '" + context.getModuleName() + "', null);\n");
          out.print("};"); 
          out.newline();
          out.print("})();");
	}

    protected void doScriptBody(LinkerContext context, DefaultTextOutput out) { 
	      out.newline(); 
	}

	protected void doScriptLicense(DefaultTextOutput out) {
		// TODO Auto-generated method stub
		
	}

	protected void doScriptHeader(LinkerContext context, DefaultTextOutput out) {
		 
		  out.print("// 玄子科技出品");
	      out.newline(); 
	      out.print("$wnd = window;$doc = document;\n"); 
	      out.print("(function () {");
	      out.newline();
	        // grab compilation result
	      out.print("var $moduleName = \"\";\r\n" + 
	        		"var $moduleBase; \r\n" );
	}

	protected void addPreloadCode(TreeLogger logger, LinkerContext context,
            ArtifactSet artifacts, CompilationResult result,
            DefaultTextOutput out) throws UnableToCompleteException {
        //noop
    }
    

}
